var express = require('express');
var router = express.Router();
var userkeys = require('../utils/userkeys');
var Users = require('../../db/UsersIf');

var LOGIN_CALLBACK = '/user/login';

var passportClient = require('../../lib/passport')({
  hostname: 'passport.test.makeblock.com',
  clientId: 'micdev',
  secret: 'mic'
});

function _getLoginUrl() {
  var url = 'http://passport.test.makeblock.com';
  url += '/oauth2/auth?state=iot&response_type=code&client_id=micdev';
  url += '&redirect_uri=' + encodeURIComponent('http://10.0.1.68:3000/user/login');
  return url;
}

function _getLogoutUrl() {
  var url = 'http://passport.test.makeblock.com/logout?redirect=';
  return url;
}

router.get('/logout', function(req, res, next) {
  if(req.session.user) {
    console.log('logout email:' + req.session.user.email);
  }
 
  req.session.user = null;
  res.redirect(_getLogoutUrl());
});

router.get('/login', function(req, res, next) {
  console.log('sessionid:' + req.session.id);
  var code = req.query.code;
  if (code) {
    console.log('code:'+ code);
    passportClient.oauth2.getAccessToken(code).then(function(token) {
      console.log(token);
      return passportClient.api.user.me(token.access_token);
    }).then(function(user) {
      req.session.user = user.user;
      return userkeys.initUser(req.session.user.id);
    }).then(function(user_key) {
      console.log('user_key:' + user_key);
      // Users.Insert(req.session.user.id, user_key, req.session.user.email);
      res.render('login.ejs', {sessionid: req.session.id, userkey: user_key, email: req.session.user.email});
    }).catch(function(err) {
      console.log(err);
      next(err);
    });
  } else {
    console.log('loginUrl:' + _getLoginUrl());
    res.redirect(_getLoginUrl());
  }
});



module.exports = router;